package com.heima.juc.n8;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

/**
 * @author : leimingchao
 * @date Date : 2022年02月20日 7:26
 */
@Slf4j(topic = "c.TestForkJoin2")
public class TestForkJoin2 {

    public static void main(String[] args) {

        ForkJoinPool forkJoinPool = new ForkJoinPool(4);
        System.out.println(forkJoinPool.invoke(new MyTask(5)));
    }
}

/**
 * 如果任务有返回值，继承RecursiveTask
 * 如果任务没有返回值，继承RecursiveAction
 *
 * 1~n之间整数的和
 */
@Slf4j(topic = "c.MyTask2")
class MyTask2 extends RecursiveTask<Integer> {

    private int begin;
    private int end;

    public MyTask2(int begin, int end) {
        this.begin = begin;
        this.end = end;
    }

    @Override
    public String toString() {
        return "{" + begin + "," + end + '}';
    }

    @Override
    protected Integer compute() {

        // 5, 5
        if (begin == end) {
            log.debug("join() {}", begin);
            return begin;
        }

        if (end - begin == 1) {
            log.debug("join() {} + {} = {}", begin, end, end + begin);
            return end + begin;
        }

        // 1 5
        // 3
        int mid = (end + begin) / 2;

        // 1,3
        MyTask2 t1 = new MyTask2(begin, mid);
        t1.fork();

        // 4,5
        MyTask2 t2 = new MyTask2(mid + 1, end);
        t2.fork();
        log.debug("fork() {} + {} = ?", t1, t2);

        int result = t1.join() + t2.join();
        log.debug("join() {} + {} = {}", t1, t2, result);
        return result;
    }
}
